class BackgroundViewer {
    constructor() {
        this.pagesData = [];
        this.currentPage = 0;
        this.filename = '';
        
        this.init();
    }
    
    init() {
        // 绑定文件上传事件
        document.getElementById('pdfInput').addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                this.uploadPDF(file);
            }
        });
        
        // 绑定按钮事件
        document.getElementById('prevPage').addEventListener('click', () => this.prevPage());
        document.getElementById('nextPage').addEventListener('click', () => this.nextPage());
        document.getElementById('downloadBtn').addEventListener('click', () => this.downloadPDF());
        document.getElementById('resetBtn').addEventListener('click', () => this.reset());
    }
    
    async uploadPDF(file) {
        this.showLoading('正在提取PDF背景...');
        
        const formData = new FormData();
        formData.append('pdf', file);
        
        try {
            const response = await fetch('/upload_pdf', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.success) {
                this.pagesData = data.pages;
                this.filename = data.filename;
                this.currentPage = 0;
                
                // 显示文件名
                document.getElementById('fileName').textContent = `已加载: ${this.filename}`;
                
                // 显示工具栏和查看器
                document.getElementById('toolbar').style.display = 'flex';
                document.getElementById('welcome').style.display = 'none';
                document.getElementById('pageViewer').style.display = 'block';
                document.getElementById('stats').style.display = 'flex';
                
                // 渲染第一页
                this.renderPage();
                
                console.log('✅ PDF背景提取成功！');
            } else {
                alert('处理失败: ' + data.error);
            }
        } catch (error) {
            console.error('上传失败:', error);
            alert('上传失败: ' + error.message);
        } finally {
            this.hideLoading();
        }
    }
    
    renderPage() {
        if (this.pagesData.length === 0) return;
        
        const pageData = this.pagesData[this.currentPage];
        const viewer = document.getElementById('pageViewer');
        
        // 清空查看器
        viewer.innerHTML = '';
        
        // 创建图片元素
        const img = document.createElement('img');
        img.src = `data:image/png;base64,${pageData.background_image}`;
        img.alt = `页面 ${this.currentPage + 1}`;
        
        viewer.appendChild(img);
        
        // 更新页面信息
        document.getElementById('pageInfo').textContent = 
            `页面: ${this.currentPage + 1} / ${this.pagesData.length}`;
        
        // 更新统计信息
        document.getElementById('textCount').textContent = pageData.text_regions_count;
        document.getElementById('imageCount').textContent = pageData.image_regions_count;
        
        // 更新按钮状态
        document.getElementById('prevPage').disabled = (this.currentPage === 0);
        document.getElementById('nextPage').disabled = (this.currentPage === this.pagesData.length - 1);
        
        console.log(`📄 显示页面 ${this.currentPage + 1}/${this.pagesData.length}`);
    }
    
    prevPage() {
        if (this.currentPage > 0) {
            this.currentPage--;
            this.renderPage();
        }
    }
    
    nextPage() {
        if (this.currentPage < this.pagesData.length - 1) {
            this.currentPage++;
            this.renderPage();
        }
    }
    
    async downloadPDF() {
        this.showLoading('正在生成纯背景PDF...');
        
        try {
            const response = await fetch('/export_pdf', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    filename: this.filename
                })
            });
            
            if (response.ok) {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `background_${this.filename}`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
                
                console.log('✅ PDF下载成功！');
            } else {
                const error = await response.json();
                alert('导出失败: ' + error.error);
            }
        } catch (error) {
            console.error('导出失败:', error);
            alert('导出失败: ' + error.message);
        } finally {
            this.hideLoading();
        }
    }
    
    reset() {
        this.pagesData = [];
        this.currentPage = 0;
        this.filename = '';
        
        document.getElementById('fileName').textContent = '';
        document.getElementById('toolbar').style.display = 'none';
        document.getElementById('pageViewer').style.display = 'none';
        document.getElementById('welcome').style.display = 'block';
        document.getElementById('stats').style.display = 'none';
        document.getElementById('pdfInput').value = '';
        
        console.log('🔄 已重置');
    }
    
    showLoading(message) {
        document.getElementById('loadingMessage').textContent = message;
        document.getElementById('loadingOverlay').style.display = 'flex';
    }
    
    hideLoading() {
        document.getElementById('loadingOverlay').style.display = 'none';
    }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    new BackgroundViewer();
});
